import { Button, Checkbox } from 'antd'
import { useEffect, useState } from 'react'

import AekModal, { PromiseThen } from '@/components/AekModal'
import { message, modal } from '@/utils/antdHelper'

import SortableTable from '../../SortableTable'

const ConfigModal = props => {
  const { columns: propsColumn, onCancel, onSubmit, onOk, onReset } = props
  const [columns, setColumns] = useState([])

  useEffect(() => {
    setColumns(
      propsColumn.map(({ children, ...other }) => ({
        expandedRowData: children,
        ...other,
      })),
    )
  }, [])

  const footer = (
    <div className='flex-justify-between flex'>
      <div>
        <Button
          onClick={() => {
            modal.confirm({
              centered: true,
              title: '确认还原',
              content: '还原后列表将恢复默认配置',
              onOk: () => {
                onReset()
                onSubmit()
              },
            })
          }}
          type='primary'
          ghost
        >
          一键还原
        </Button>
      </div>
      <div>
        <Button onClick={onCancel}>取消</Button>
        <Button
          type='primary'
          onClick={() => {
            const allHide = columns.every(item => item.hide)
            if (allHide) {
              message.error('请至少保留一列')
              return
            }
            columns.forEach(item => {
              item.children = item.expandedRowData
            })
            onOk(columns)
            onSubmit()
          }}
        >
          确定
        </Button>
      </div>
    </div>
  )

  return (
    <AekModal title='列表配置' width={500} footer={footer}>
      <SortableTable
        pagination={false}
        dataSource={columns}
        scroll={{ y: 500 }}
        columns={[
          {
            title: '字段名称',
            dataIndex: 'title',
            className: 'drag-visible',
          },
          {
            title: '是否展示',
            key: 'show',
            className: 'text-center',
            width: 90,
            render: row => (
              <Checkbox
                checked={!row.hide}
                onClick={e => {
                  const { checked } = e.target
                  row.hide = !checked
                  // const colsCopy = cloneDeep(columns)
                  // 这里不用cloneDeep的原因是因为有可能传入react对象，层级深，导致clone慢，
                  // 通常情况下，使用该组件，需要修改的值为非对象，故暂时如下处理
                  const colsCopy = columns.map(column => {
                    return { ...column }
                  })
                  setColumns(colsCopy)
                }}
              />
            ),
          },
        ]}
        onChange={newData => setColumns(newData)}
      />
    </AekModal>
  )
}

ConfigModal.PromiseThen = PromiseThen

export default ConfigModal
